//这个混入用于初始化位置权限，获取当前位置经纬度
// import { showOkCancelDialog } from "../utils/dialogUtils";
import { globalKeys } from "@/global/globalKeys";

export const locationMixin = {
    data() {
        return {
            curLatitude: '',
            curLongitude: '',

            //腾讯地图逆地址解析
            // QQMapWX: require('@/qqmap/qqmap-wx-jssdk.min'),

            //用户当前所处市级
            curCity: '',
            //到目标地址距离
            distance: '',
            //选取的位置
            choosedAddress: "",
            choosedAddressInfo: {},
              //选取用户
            choosedAddressTwo: "",
            choosedAddressInfoTwo: {},
        }
    },


    methods: {
        //初始化位置授权
        initLocPermission(callback) {
            let that = this
            uni.authorize({
                scope: 'scope.userLocation',
                success(res) {
                    //存储获得授权flag
                    console.log('调用initLocPermission,并且成功获得授权')
                    uni.setStorageSync(globalKeys.KEY_GET_LOC_PERMISSION, 1)

                    if (callback)
                        callback()

                },
                // 授权失败
                fail(err) {
                    console.log("授权失败err", err);
                    uni.showModal({
                        title: '提示',
                        content: '未获取到位置授权，是否授权位置信息？',
                        showCancel: true,
                        success: ({ confirm, cancel }) => {
                            if (confirm) {
                                uni.openSetting({
                                    success(res) {
                                        console.log('openSetting成功回调，res=', res)

                                        // 如果用户授权了地理信息在，则提示授权成功
                                        if (res.authSetting['scope.userLocation'] === true) {
                                            //存储获得授权flag
                                            uni.setStorageSync(globalKeys.KEY_GET_LOC_PERMISSION, 1)

                                            if (callback)
                                                callback()
                                        } else {

                                            uni.showToast({
                                                title: "授权失败",
                                                icon: "none",
                                                duration: 1500
                                            })
                                        }
                                    },
                                    fail(err) {
                                        uni.showToast({
                                            title: "未授权位置信息~",
                                            icon: "none",
                                            duration: 1500
                                        })
                                        console.log("未获得授权", err);
                                    }
                                })
                            }

                        }
                    })



                }
            })
        },

        //获取当前位置
        getCurrentLocation(successCallback) {
            let that = this
            uni.getLocation({
                // #ifdef MP-WEIXIN
                type: "gcj02",   // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
                // #endif
                success: function (res) {
                    console.log('获取的当前位置信息：', res)
                    that.curLongitude = res.longitude
                    that.curLatitude = res.latitude
                    // getApp().globalData[globalKeys.CUR_LATITUDE] = res.latitude
                    // getApp().globalData[globalKeys.CUR_LONGITUDE] = res.longitude
                    //开发测试固定位置
                    // that.curLongitude = "114.4215311"
                    // that.curLatitude = "30.4715811"
                    // getApp().globalData[globalKeys.CUR_LATITUDE] = "30.4715811"
                    // getApp().globalData[globalKeys.CUR_LONGITUDE] = "114.4215311"
                    // uni.setStorageSync(globalKeys.KEY_GET_LOC_PERMISSION, 1)
                    if (successCallback)
                        successCallback()
                },
                fail: err => {
                    console.log('获取当前位置失败:', err)
                    if (err.errMsg.includes('ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF')) {
                        // showOkCancelDialog({
                        //     title: '提示',
                        //     content: '获取当前位置失败，请检查您是否打开了系统定位开关',
                        //     cancelText: '取消',
                        //     confirmText: '确定',
                        //     showCancel: false,
                        // })
                        return
                    }
                }
            })
        },

        //选取当前位置
        chooseLocation(successCallback, failCallback) {
            uni.chooseLocation({
                success: res => {
                    console.log('选取位置成功：', res)
                    if (successCallback)
                        successCallback(res)
                },
                fail: err => {
                    console.log('选取位置失败：', err)
                    if (failCallback)
                        failCallback(err)
                }
            })
        },

        //使用腾讯位置服务，根据经纬度查询具体位置
        resolveLatLong(latitude, longitude) {
            let that = this
            let qqmap = new this.QQMapWX({
                key: getApp().globalData.QQMAP_KEY
            })
            qqmap.reverseGeocoder({
                location: {
                    latitude,
                    longitude
                },
                success: function (res) {
                    console.log('根据经纬度坐标解析的地址返回值：', res)
                    that.curCity = res.result.address_component.city
                    console.log('根据经纬度坐标解析的当前城市：', that.curCity)

                    //保存当前位置到本地，（需要缓存，因为解析经纬度服务有次数限制，不能每次打开页面都去解析经纬度）
                    //that.saveCurrentLocation()

                    //搜索自提点页面，暂时不设计缓存，因为需要实时定位当前位置
                },

                fail: function (error) {
                    console.error('解析坐标异常：', error);

                    uni.showToast({
                        title: '获取位置失败',
                        icon: 'none'
                    })
                },
            })
        },
        //使用腾讯地图计算 2个精纬度之间的距离
        getDistance(lat, lng) {
            let that = this
            let qqmap = new this.QQMapWX({
                key: getApp().globalData.QQMAP_KEY
            })
            qqmap.calculateDistance({
                from: '',//出发地址，默认为当前地址
                to: lat + "," + lng,//目标地址
                success: (res) => {//成功后的回调
                    if (res.status === 0) {
                        this.distance = res.result.elements[0].distance
                        if (String(this.distance).length < 4) {
                            this.distance = this.distance + "米"
                        } else {
                            this.distance = (this.distance / 1000).toFixed(1) + "千米"
                        }
                        console.log("与目标地址距离:", this.distance);
                    }
                },
                fail: function (error) {
                    console.error("error", error);
                },

            })
        },
        //选择地理位置
        getSelectLocation() {
            let bGetLocPermission = uni.getStorageSync("bGetLocPermission") == 1;
            console.log("🚀 ~ bGetLocPermission", bGetLocPermission)

            if (bGetLocPermission) {
                this.chooseLocation((res) => {
                    this.choosedAddress = res.address;
                    this.choosedAddressInfo = res;
                });
            } else {
                this.initLocPermission(() => {
                    this.chooseLocation((res) => {
                        this.choosedAddress = res.address;
                        this.choosedAddressInfo = res;
                    });
                });
            }
        },
        //选择用户名
        getSelectLocationTwo() {
            let bGetLocPermission = uni.getStorageSync("bGetLocPermission") == 1;
            console.log("🚀 ~ bGetLocPermission", bGetLocPermission)

            if (bGetLocPermission) {
                this.chooseLocation((res) => {
                    this.choosedAddressTwo = res.address;
                    this.choosedAddressInfoTwo = res;
                });
            } else {
                this.initLocPermission(() => {
                    this.chooseLocation((res) => {
                        this.choosedAddressTwo = res.address;
                        this.choosedAddressInfoTwo = res;
                    });
                });
            }
        }
        
    }
}
